#!/opt/bin/python

import os, sys, urllib

print '<?xml version="1.0" encoding="UTF-8"?><atv>'

album = ('QUERY_STRING' in os.environ)
uri = os.environ['QUERY_STRING'] if album else 'media/DATA/Pictures'
dir = '/opt/etc/www/' + urllib.unquote(uri)
files = os.listdir(dir) if os.path.isdir(dir) else []
files.sort(None, None, not album)

if album:
	count = 0
	for f in files:
		if os.path.splitext(f)[1] in ('.jpg', '.png'):
			count += 1

	print '<head><script src="http://router/appletv/us/js/browser.js"/></head>'
	print '<body><mediaBrowser id="browser" gridLayout="mixed">'
	print '<header><headerWithCountAndButtons>'
	print '<title>%s</title><count>%d</count>' % (os.path.basename(dir), count)
	print '<buttons><actionButton id="slideshow" onSelect="onSettingsSelection()" onPlay="onSlideshowStart()">'
	print '<title>%s</title>' % urllib.unquote('%E5%B9%BB%E7%81%AF%E7%89%87%E6%92%AD%E6%94%BE')
	print '</actionButton></buttons>'
	print '</headerWithCountAndButtons></header>'
	print '<items>'

	i = 0
	for f in files:
		if os.path.splitext(f)[1] in ('.jpg', '.png'):
			i += 1
			print '<photo id="photo%d" onSelect="onPhotoSelection(\'photo%d\')" onPlay="onSlideshowStart(\'photo%d\')">' % (i, i, i)
			print '<assets><photoAsset width="486" height="720" src="http://router/%s/%s" /></assets>' % (uri, urllib.quote(f))
			print '</photo>'

	print '</items></mediaBrowser>'

else:
	print '<body><scroller id="scroller"><items><grid columnCount="5" id="grid"><items>'
	i = 0
	for f in files:
		dir2 = dir + '/' + f
		if os.path.isdir(dir2):
			files2 = os.listdir(dir2)
			files2.sort()
			for f2 in files2:
				if os.path.splitext(f2)[1] in ('.jpg', '.png'):
					i += 1
					url = 'http://router/appletv/photo.py?' + uri + '/' + urllib.quote(f)
					print '<sixteenByNinePoster alwaysShowTitles="true" id="album%d" onPlay="atv.loadURL(\'%s\')" onSelect="atv.loadURL(\'%s\')">' % (i, url, url)
					print '<title>%s</title>' % f
					thumb = 'appletv/thumb' if os.path.isfile('/opt/etc/www/appletv/thumb/' + f2) else uri + '/' + urllib.quote(f)
					print '<image>http://router/%s/%s</image>' % (thumb, urllib.quote(f2))
					print '<defaultImage>resource://Poster.png</defaultImage>'
					print '</sixteenByNinePoster>'
					break
	print '</items></grid></items></scroller>'

print '</body></atv>'
